// internal/api/handlers/storage_handler.go
package handlers

import (
	"io"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"

	"virt-manager-go/internal/console"
	"virt-manager-go/internal/domain"
)

type StorageHandler struct {
	storageService domain.StoragePoolService
	logger         *logrus.Logger
}

func NewStorageHandler(storageService domain.StoragePoolService, logger *logrus.Logger) *StorageHandler {
	return &StorageHandler{
		storageService: storageService,
		logger:         logger,
	}
}

// ListPools 列出存储池
//
//	@Summary		获取存储池列表
//	@Description	获取指定连接的所有存储池
//	@Tags			Storage
//	@Param			connection_id	path		string					true	"连接ID"
//	@Success		200				{object}	map[string]interface{}	"返回存储池列表"
//	@Failure		500				{object}	map[string]string		"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools [get]
func (h *StorageHandler) ListPools(c *gin.Context) {
	connID := c.Param("connection_id")

	pools, err := h.storageService.ListPools(c.Request.Context(), connID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": pools, "count": len(pools)})
}

// CreatePool 创建存储池
//
//	@Summary		创建存储池
//	@Description	根据配置创建新的存储池
//	@Tags			Storage
//	@Param			connection_id	path		string						true	"连接ID"
//	@Param			config			body		domain.StoragePoolConfig	true	"存储池配置"
//	@Success		201				{object}	map[string]interface{}		"创建成功，返回存储池信息"
//	@Failure		400				{object}	map[string]string			"请求参数错误"
//	@Failure		500				{object}	map[string]string			"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools [post]
func (h *StorageHandler) CreatePool(c *gin.Context) {
	connID := c.Param("connection_id")

	var config domain.StoragePoolConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	pool, err := h.storageService.CreatePool(c.Request.Context(), connID, &config)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"data": pool})
}

// GetPool 获取存储池信息
//
//	@Summary		获取存储池详情
//	@Description	获取指定存储池的详细信息
//	@Tags			Storage
//	@Param			connection_id	path		string					true	"连接ID"
//	@Param			pool_name		path		string					true	"存储池名称"
//	@Success		200				{object}	map[string]interface{}	"返回存储池详细信息"
//	@Failure		500				{object}	map[string]string		"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name} [get]
func (h *StorageHandler) GetPool(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")

	pool, err := h.storageService.GetPool(c.Request.Context(), connID, poolName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": pool})
}

// DeletePool 删除存储池
//
//	@Summary		删除存储池
//	@Description	删除指定的存储池
//	@Tags			Storage
//	@Param			connection_id	path		string				true	"连接ID"
//	@Param			pool_name		path		string				true	"存储池名称"
//	@Success		200				{object}	map[string]string	"删除成功"
//	@Failure		500				{object}	map[string]string	"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name} [delete]
func (h *StorageHandler) DeletePool(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")

	if err := h.storageService.DeletePool(c.Request.Context(), connID, poolName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Storage pool deleted successfully"})
}

// StartPool 启动存储池
//
//	@Summary		启动存储池
//	@Description	启动指定的存储池
//	@Tags			Storage
//	@Param			connection_id	path		string				true	"连接ID"
//	@Param			pool_name		path		string				true	"存储池名称"
//	@Success		200				{object}	map[string]string	"启动成功"
//	@Failure		500				{object}	map[string]string	"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name}/start [post]
func (h *StorageHandler) StartPool(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")

	if err := h.storageService.StartPool(c.Request.Context(), connID, poolName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Storage pool started successfully"})
}

// StopPool 停止存储池
//
//	@Summary		停止存储池
//	@Description	停止指定的存储池
//	@Tags			Storage
//	@Param			connection_id	path		string				true	"连接ID"
//	@Param			pool_name		path		string				true	"存储池名称"
//	@Success		200				{object}	map[string]string	"停止成功"
//	@Failure		500				{object}	map[string]string	"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name}/stop [post]
func (h *StorageHandler) StopPool(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")

	if err := h.storageService.StopPool(c.Request.Context(), connID, poolName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Storage pool stopped successfully"})
}

// RefreshPool 刷新存储池
//
//	@Summary		刷新存储池
//	@Description	刷新指定存储池的状态
//	@Tags			Storage
//	@Param			connection_id	path		string				true	"连接ID"
//	@Param			pool_name		path		string				true	"存储池名称"
//	@Success		200				{object}	map[string]string	"刷新成功"
//	@Failure		500				{object}	map[string]string	"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name}/refresh [post]
func (h *StorageHandler) RefreshPool(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")

	if err := h.storageService.RefreshPool(c.Request.Context(), connID, poolName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Storage pool refreshed successfully"})
}

// ListVolumes 列出存储卷
//
//	@Summary		获取存储卷列表
//	@Description	获取指定存储池中的所有存储卷
//	@Tags			Storage
//	@Param			connection_id	path		string					true	"连接ID"
//	@Param			pool_name		path		string					true	"存储池名称"
//	@Success		200				{object}	map[string]interface{}	"返回存储卷列表"
//	@Failure		500				{object}	map[string]string		"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name}/volumes [get]
func (h *StorageHandler) ListVolumes(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")

	volumes, err := h.storageService.ListVolumes(c.Request.Context(), connID, poolName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": volumes, "count": len(volumes)})
}

// CreateVolume 创建存储卷
//
//	@Summary		创建存储卷
//	@Description	在指定存储池中创建新的存储卷
//	@Tags			Storage
//	@Param			connection_id	path		string						true	"连接ID"
//	@Param			pool_name		path		string						true	"存储池名称"
//	@Param			config			body		domain.StorageVolumeConfig	true	"存储卷配置"
//	@Success		201				{object}	map[string]interface{}		"创建成功，返回存储卷信息"
//	@Failure		400				{object}	map[string]string			"请求参数错误"
//	@Failure		500				{object}	map[string]string			"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name}/volumes [post]
func (h *StorageHandler) CreateVolume(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")

	var config domain.StorageVolumeConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	volume, err := h.storageService.CreateVolume(c.Request.Context(), connID, poolName, &config)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"data": volume})
}

// GetVolume 获取存储卷信息
//
//	@Summary		获取存储卷详情
//	@Description	获取指定存储卷的详细信息
//	@Tags			Storage
//	@Param			connection_id	path		string					true	"连接ID"
//	@Param			pool_name		path		string					true	"存储池名称"
//	@Param			volume_name		path		string					true	"存储卷名称"
//	@Success		200				{object}	map[string]interface{}	"返回存储卷详细信息"
//	@Failure		500				{object}	map[string]string		"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name}/volumes/{volume_name} [get]
func (h *StorageHandler) GetVolume(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")
	volumeName := c.Param("volume_name")

	volume, err := h.storageService.GetVolume(c.Request.Context(), connID, poolName, volumeName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": volume})
}

// DeleteVolume 删除存储卷
//
//	@Summary		删除存储卷
//	@Description	删除指定的存储卷
//	@Tags			Storage
//	@Param			connection_id	path		string				true	"连接ID"
//	@Param			pool_name		path		string				true	"存储池名称"
//	@Param			volume_name		path		string				true	"存储卷名称"
//	@Success		200				{object}	map[string]string	"删除成功"
//	@Failure		500				{object}	map[string]string	"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name}/volumes/{volume_name} [delete]
func (h *StorageHandler) DeleteVolume(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")
	volumeName := c.Param("volume_name")

	if err := h.storageService.DeleteVolume(c.Request.Context(), connID, poolName, volumeName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Storage volume deleted successfully"})
}

// CloneVolume 克隆存储卷
//
//	@Summary		克隆存储卷
//	@Description	将指定存储卷克隆为新存储卷
//	@Tags			Storage
//	@Param			connection_id	path		string				true	"连接ID"
//	@Param			pool_name		path		string				true	"存储池名称"
//	@Param			volume_name		path		string				true	"源存储卷名称"
//	@Param			request			body		map[string]string	true	"克隆请求，包含新名称"
//	@Success		200				{object}	map[string]string	"克隆成功"
//	@Failure		400				{object}	map[string]string	"请求参数错误"
//	@Failure		500				{object}	map[string]string	"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name}/volumes/{volume_name}/clone [post]
func (h *StorageHandler) CloneVolume(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")
	volumeName := c.Param("volume_name")

	var req struct {
		NewName string `json:"new_name" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	err := h.storageService.CloneVolume(c.Request.Context(), connID, poolName, volumeName, req.NewName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "Storage volume cloned successfully"})
}

// ResizeVolume 调整存储卷大小
//
//	@Summary		调整存储卷大小
//	@Description	调整指定存储卷的大小
//	@Tags			Storage
//	@Param			connection_id	path		string				true	"连接ID"
//	@Param			pool_name		path		string				true	"存储池名称"
//	@Param			volume_name		path		string				true	"存储卷名称"
//	@Param			request			body		map[string]uint64	true	"调整请求，包含新大小"
//	@Success		200				{object}	map[string]string	"调整成功"
//	@Failure		400				{object}	map[string]string	"请求参数错误"
//	@Failure		500				{object}	map[string]string	"服务器内部错误"
//	@Router			/connections/{connection_id}/storage/pools/{pool_name}/volumes/{volume_name}/resize [post]
func (h *StorageHandler) ResizeVolume(c *gin.Context) {
	connID := c.Param("connection_id")
	poolName := c.Param("pool_name")
	volumeName := c.Param("volume_name")

	var req struct {
		NewSize uint64 `json:"new_size" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}
	if err := h.storageService.ResizeVolume(c.Request.Context(), connID, poolName, volumeName, req.NewSize); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "Storage volume resized successfully"})
}

// NetworkHandler 网络处理器
type NetworkHandler struct {
	networkService domain.NetworkService
	logger         *logrus.Logger
}

func NewNetworkHandler(networkService domain.NetworkService, logger *logrus.Logger) *NetworkHandler {
	return &NetworkHandler{
		networkService: networkService,
		logger:         logger,
	}
}

// ListNetworks 列出虚拟网络
//
//	@Summary		List virtual networks
//	@Description	List all virtual networks for a connection
//	@Tags			Network
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/networks [get]
func (h *NetworkHandler) ListNetworks(c *gin.Context) {
	connID := c.Param("connection_id")

	networks, err := h.networkService.ListNetworks(c.Request.Context(), connID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": networks, "count": len(networks)})
}

// CreateNetwork 创建虚拟网络
//
//	@Summary		Create a virtual network
//	@Description	Create a new virtual network
//	@Tags			Network
//	@Param			connection_id	path		string					true	"Connection ID"
//	@Param			config			body		domain.NetworkConfig	true	"Network Configuration"
//	@Success		201				{object}	map[string]interface{}
//	@Failure		400				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/networks [post]
func (h *NetworkHandler) CreateNetwork(c *gin.Context) {
	connID := c.Param("connection_id")

	var config domain.NetworkConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	network, err := h.networkService.CreateNetwork(c.Request.Context(), connID, &config)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"data": network})
}

// GetNetwork 获取虚拟网络信息
//
//	@Summary		Get virtual network details
//	@Description	Get detailed information about a virtual network
//	@Tags			Network
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			network_name	path		string	true	"Network Name"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/networks/{network_name} [get]
func (h *NetworkHandler) GetNetwork(c *gin.Context) {
	connID := c.Param("connection_id")
	networkName := c.Param("network_name")

	network, err := h.networkService.GetNetwork(c.Request.Context(), connID, networkName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": network})

}

// DeleteNetwork 删除虚拟网络
//
//	@Summary		Delete a virtual network
//	@Description	Delete a virtual network
//	@Tags			Network
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			network_name	path		string	true	"Network Name"
//	@Success		200				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/networks/{network_name} [delete]
func (h *NetworkHandler) DeleteNetwork(c *gin.Context) {
	connID := c.Param("connection_id")
	networkName := c.Param("network_name")

	if err := h.networkService.DeleteNetwork(c.Request.Context(), connID, networkName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Network deleted successfully"})
}

// StartNetwork 启动虚拟网络
//
//	@Summary		Start a virtual network
//	@Description	Start a virtual network
//	@Tags			Network
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			network_name	path		string	true	"Network Name"
//	@Success		200				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/networks/{network_name}/start [post]
func (h *NetworkHandler) StartNetwork(c *gin.Context) {
	connID := c.Param("connection_id")
	networkName := c.Param("network_name")

	if err := h.networkService.StartNetwork(c.Request.Context(), connID, networkName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Network started successfully"})
}

// StopNetwork 停止虚拟网络
//
//	@Summary		Stop a virtual network
//	@Description	Stop a virtual network
//	@Tags			Network
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			network_name	path		string	true	"Network Name"
//	@Success		200				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/networks/{network_name}/stop [post]
func (h *NetworkHandler) StopNetwork(c *gin.Context) {
	connID := c.Param("connection_id")
	networkName := c.Param("network_name")

	if err := h.networkService.StopNetwork(c.Request.Context(), connID, networkName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Network stopped successfully"})
}

// GetDHCPLeases 获取 DHCP 租约
//
//	@Summary		Get DHCP leases
//	@Description	Get DHCP leases for a network
//	@Tags			Network
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			network_name	path		string	true	"Network Name"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/networks/{network_name}/dhcp [get]
func (h *NetworkHandler) GetDHCPLeases(c *gin.Context) {
	connID := c.Param("connection_id")
	networkName := c.Param("network_name")

	leases, err := h.networkService.GetDHCPLeases(c.Request.Context(), connID, networkName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": leases, "count": len(leases)})
}

// SnapshotHandler 快照处理器
type SnapshotHandler struct {
	snapshotService domain.SnapshotService
	logger          *logrus.Logger
}

func NewSnapshotHandler(snapshotService domain.SnapshotService, logger *logrus.Logger) *SnapshotHandler {
	return &SnapshotHandler{
		snapshotService: snapshotService,
		logger:          logger,
	}
}

// ListSnapshots 列出快照
//
//	@Summary		List snapshots
//	@Description	List all snapshots for a VM
//	@Tags			Snapshot
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			vm_name			path		string	true	"VM Name"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/vms/{vm_name}/snapshots [get]
func (h *SnapshotHandler) ListSnapshots(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")

	snapshots, err := h.snapshotService.ListSnapshots(c.Request.Context(), connID, vmName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": snapshots, "count": len(snapshots)})
}

// CreateSnapshot 创建快照
//
//	@Summary		Create a snapshot
//	@Description	Create a new snapshot for a VM
//	@Tags			Snapshot
//	@Param			connection_id	path		string					true	"Connection ID"
//	@Param			vm_name			path		string					true	"VM Name"
//	@Param			config			body		domain.SnapshotConfig	true	"Snapshot Configuration"
//	@Success		201				{object}	map[string]interface{}
//	@Failure		400				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/vms/{vm_name}/snapshots [post]
func (h *SnapshotHandler) CreateSnapshot(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")

	var config domain.SnapshotConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	snapshot, err := h.snapshotService.CreateSnapshot(c.Request.Context(), connID, vmName, &config)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"data": snapshot})
}

// GetSnapshot 获取快照信息
//
//	@Summary		Get snapshot details
//	@Description	Get detailed information about a snapshot
//	@Tags			Snapshot
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			vm_name			path		string	true	"VM Name"
//	@Param			snapshot_name	path		string	true	"Snapshot Name"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/vms/{vm_name}/snapshots/{snapshot_name} [get]
func (h *SnapshotHandler) GetSnapshot(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")
	snapshotName := c.Param("snapshot_name")

	snapshot, err := h.snapshotService.GetSnapshot(c.Request.Context(), connID, vmName, snapshotName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": snapshot})
}

// DeleteSnapshot 删除快照
//
//	@Summary		Delete a snapshot
//	@Description	Delete a snapshot
//	@Tags			Snapshot
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			vm_name			path		string	true	"VM Name"
//	@Param			snapshot_name	path		string	true	"Snapshot Name"
//	@Param			delete_children	query		boolean	false	"Delete child snapshots"
//	@Success		200				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/vms/{vm_name}/snapshots/{snapshot_name} [delete]
func (h *SnapshotHandler) DeleteSnapshot(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")
	snapshotName := c.Param("snapshot_name")
	deleteChildren := c.Query("delete_children") == "true"

	if err := h.snapshotService.DeleteSnapshot(c.Request.Context(), connID, vmName, snapshotName, deleteChildren); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Snapshot deleted successfully"})
}

// RevertToSnapshot 恢复到快照
//
//	@Summary		Revert to snapshot
//	@Description	Revert VM to a snapshot state
//	@Tags			Snapshot
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			vm_name			path		string	true	"VM Name"
//	@Param			snapshot_name	path		string	true	"Snapshot Name"
//	@Success		200				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/vms/{vm_name}/snapshots/{snapshot_name}/revert [post]
func (h *SnapshotHandler) RevertToSnapshot(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")
	snapshotName := c.Param("snapshot_name")

	if err := h.snapshotService.RevertToSnapshot(c.Request.Context(), connID, vmName, snapshotName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Reverted to snapshot successfully"})
}

// MigrationHandler 迁移处理器
type MigrationHandler struct {
	migrationService domain.MigrationService
	logger           *logrus.Logger
}

func NewMigrationHandler(migrationService domain.MigrationService, logger *logrus.Logger) *MigrationHandler {
	return &MigrationHandler{
		migrationService: migrationService,
		logger:           logger,
	}
}

// MigrateVM 迁移虚拟机
//
//	@Summary		Migrate VM
//	@Description	Migrate a VM to another host
//	@Tags			Migration
//	@Param			connection_id	path		string					true	"Source Connection ID"
//	@Param			vm_name			path		string					true	"VM Name"
//	@Param			request			body		map[string]interface{}	true	"Migration request with destination URI and config"
//	@Success		202				{object}	map[string]interface{}
//	@Failure		400				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/vms/{vm_name}/migrate [post]
func (h *MigrationHandler) MigrateVM(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")

	var req struct {
		DestURI string                  `json:"dest_uri" binding:"required"`
		Config  *domain.MigrationConfig `json:"config"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if req.Config == nil {
		req.Config = &domain.MigrationConfig{Live: true}
	}

	job, err := h.migrationService.MigrateVM(c.Request.Context(), connID, vmName, req.DestURI, req.Config)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusAccepted, gin.H{"data": job})
}

// GetMigrationStatus 获取迁移状态
//
//	@Summary		Get migration status
//	@Description	Get the status of a migration job
//	@Tags			Migration
//	@Param			job_id	path		string	true	"Migration Job ID"
//	@Success		200		{object}	map[string]interface{}
//	@Failure		404		{object}	map[string]string
//	@Router			/migration/{job_id} [get]
func (h *MigrationHandler) GetMigrationStatus(c *gin.Context) {
	jobID := c.Param("job_id")

	status, err := h.migrationService.GetMigrationStatus(c.Request.Context(), jobID)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": status})
}

// CancelMigration 取消迁移
//
//	@Summary		Cancel migration
//	@Description	Cancel a running migration job
//	@Tags			Migration
//	@Param			job_id	path		string	true	"Migration Job ID"
//	@Success		200		{object}	map[string]string
//	@Failure		500		{object}	map[string]string
//	@Router			/migration/{job_id}/cancel [post]
func (h *MigrationHandler) CancelMigration(c *gin.Context) {
	jobID := c.Param("job_id")

	if err := h.migrationService.CancelMigration(c.Request.Context(), jobID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Migration cancelled successfully"})
}

// BatchHandler 批量操作处理器
type BatchHandler struct {
	batchService domain.BatchService
	logger       *logrus.Logger
}

func NewBatchHandler(batchService domain.BatchService, logger *logrus.Logger) *BatchHandler {
	return &BatchHandler{
		batchService: batchService,
		logger:       logger,
	}
}

// BatchStartVMs 批量启动虚拟机
//
//	@Summary		Batch start VMs
//	@Description	Start multiple VMs in batch
//	@Tags			Batch
//	@Param			connection_id	path		string				true	"Connection ID"
//	@Param			request			body		map[string][]string	true	"Batch start request with VM names"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		400				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/batch/vms/start [post]
func (h *BatchHandler) BatchStartVMs(c *gin.Context) {
	connID := c.Param("connection_id")

	var req struct {
		VMNames []string `json:"vm_names" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	result, err := h.batchService.BatchStartVMs(c.Request.Context(), connID, req.VMNames)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": result})
}

// BatchStopVMs 批量停止虚拟机
//
//	@Summary		Batch stop VMs
//	@Description	Stop multiple VMs in batch
//	@Tags			Batch
//	@Param			connection_id	path		string					true	"Connection ID"
//	@Param			request			body		map[string]interface{}	true	"Batch stop request with VM names and force flag"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		400				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/batch/vms/stop [post]
func (h *BatchHandler) BatchStopVMs(c *gin.Context) {
	connID := c.Param("connection_id")

	var req struct {
		VMNames []string `json:"vm_names" binding:"required"`
		Force   bool     `json:"force"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	result, err := h.batchService.BatchStopVMs(c.Request.Context(), connID, req.VMNames, req.Force)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": result})
}

// BatchRebootVMs 批量重启虚拟机
//
//	@Summary		Batch reboot VMs
//	@Description	Reboot multiple VMs in batch
//	@Tags			Batch
//	@Param			connection_id	path		string				true	"Connection ID"
//	@Param			request			body		map[string][]string	true	"Batch reboot request with VM names"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		400				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/batch/vms/reboot [post]
func (h *BatchHandler) BatchRebootVMs(c *gin.Context) {
	connID := c.Param("connection_id")

	var req struct {
		VMNames []string `json:"vm_names" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	result, err := h.batchService.BatchRebootVMs(c.Request.Context(), connID, req.VMNames)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": result})

}

// BatchDeleteVMs 批量删除虚拟机
//
//	@Summary		Batch delete VMs
//	@Description	Delete multiple VMs in batch
//	@Tags			Batch
//	@Param			connection_id	path		string					true	"Connection ID"
//	@Param			request			body		map[string]interface{}	true	"Batch delete request with VM names and force flag"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		400				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/batch/vms/delete [post]
func (h *BatchHandler) BatchDeleteVMs(c *gin.Context) {
	connID := c.Param("connection_id")

	var req struct {
		VMNames []string `json:"vm_names" binding:"required"`
		Force   bool     `json:"force"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	result, err := h.batchService.BatchDeleteVMs(c.Request.Context(), connID, req.VMNames, req.Force)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": result})
}

// BatchCreateSnapshots 批量创建快照
//
//	@Summary		Batch create snapshots
//	@Description	Create snapshots for multiple VMs in batch
//	@Tags			Batch
//	@Param			connection_id	path		string					true	"Connection ID"
//	@Param			request			body		map[string]interface{}	true	"Batch snapshot request with VM names and config"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		400				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/batch/snapshots/create [post]
func (h *BatchHandler) BatchCreateSnapshots(c *gin.Context) {
	connID := c.Param("connection_id")

	var req struct {
		VMNames []string               `json:"vm_names" binding:"required"`
		Config  *domain.SnapshotConfig `json:"config" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	result, err := h.batchService.BatchCreateSnapshots(c.Request.Context(), connID, req.VMNames, req.Config)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": result})
}

// BatchDeleteSnapshots 批量删除快照
//
//	@Summary		Batch delete snapshots
//	@Description	Delete snapshots for multiple VMs in batch
//	@Tags			Batch
//	@Param			connection_id	path		string						true	"Connection ID"
//	@Param			request			body		[]domain.SnapshotOperation	true	"Batch snapshot delete request"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		400				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/batch/snapshots/delete [post]
func (h *BatchHandler) BatchDeleteSnapshots(c *gin.Context) {
	// TODO: 实现批量删除快照
	c.JSON(http.StatusNotImplemented, gin.H{"message": "Not implemented"})
}

// BatchUpdateVMs 批量更新虚拟机
//
//	@Summary		Batch update VMs
//	@Description	Update configuration for multiple VMs in batch
//	@Tags			Batch
//	@Param			connection_id	path		string				true	"Connection ID"
//	@Param			request			body		[]domain.VMUpdate	true	"Batch update request with VM updates"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		400				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/batch/vms/update [post]
func (h *BatchHandler) BatchUpdateVMs(c *gin.Context) {
	// TODO: 实现批量更新虚拟机
	c.JSON(http.StatusNotImplemented, gin.H{"message": "Not implemented"})
}

// GetBatchStatus 获取批量操作状态
//
//	@Summary		Get batch operation status
//	@Description	Get the status of a batch operation
//	@Tags			Batch
//	@Param			job_id	path		string	true	"Batch Job ID"
//	@Success		200		{object}	map[string]interface{}
//	@Failure		404		{object}	map[string]string
//	@Router			/batch/{job_id} [get]
func (h *BatchHandler) GetBatchStatus(c *gin.Context) {
	jobID := c.Param("job_id")

	status, err := h.batchService.GetBatchStatus(c.Request.Context(), jobID)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": status})
}

// EventHandler 事件处理器
type EventHandler struct {
	eventService domain.EventService
	logger       *logrus.Logger
}

func NewEventHandler(eventService domain.EventService, logger *logrus.Logger) *EventHandler {
	return &EventHandler{
		eventService: eventService,
		logger:       logger,
	}
}

// SubscribeEvents 订阅事件 (SSE)
//
//	@Summary		Subscribe to events
//	@Description	Subscribe to real-time events using Server-Sent Events (SSE)
//	@Tags			Event
//	@Param			filter	body		domain.EventFilter	false	"Event filter"
//	@Success		200		{string}	string				"text/event-stream"
//	@Failure		500		{object}	map[string]string
//	@Router			/events/subscribe [post]
func (h *EventHandler) SubscribeEvents(c *gin.Context) {
	var filter domain.EventFilter
	if err := c.ShouldBindJSON(&filter); err != nil {
		// 如果没有提供过滤器，使用默认（所有事件）
		filter = domain.EventFilter{}
	}

	eventCh, err := h.eventService.Subscribe(c.Request.Context(), &filter)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 设置 SSE 响应头
	c.Header("Content-Type", "text/event-stream")
	c.Header("Cache-Control", "no-cache")
	c.Header("Connection", "keep-alive")
	c.Header("X-Accel-Buffering", "no")

	// 流式发送事件
	c.Stream(func(w io.Writer) bool {
		select {
		case event, ok := <-eventCh:
			if !ok {
				return false
			}
			c.SSEvent("event", event)
			return true
		case <-c.Request.Context().Done():
			return false
		}
	})
}

// GetEvents 获取历史事件
//
//	@Summary		Get historical events
//	@Description	Get historical events with optional filtering
//	@Tags			Event
//	@Param			filter	body		domain.EventFilter	false	"Event filter"
//	@Param			limit	query		int					false	"Limit number of events"	default(100)
//	@Success		200		{object}	map[string]interface{}
//	@Failure		500		{object}	map[string]string
//	@Router			/events [post]
func (h *EventHandler) GetEvents(c *gin.Context) {
	var filter domain.EventFilter
	if err := c.ShouldBindJSON(&filter); err != nil {
		// 使用查询参数作为过滤器
		filter = domain.EventFilter{}
	}

	limit := 100
	if l := c.Query("limit"); l != "" {
		if parsed, err := strconv.Atoi(l); err == nil {
			limit = parsed
		}
	}

	events, err := h.eventService.GetEvents(c.Request.Context(), &filter, limit)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": events, "count": len(events)})
}

// StartEventListener 启动事件监听
//
//	@Summary		Start event listener
//	@Description	Start listening for events on a connection
//	@Tags			Event
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Success		200				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/events/start [post]
func (h *EventHandler) StartEventListener(c *gin.Context) {
	connID := c.Param("connection_id")

	if err := h.eventService.StartListening(c.Request.Context(), connID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Event listener started"})
}

// StopEventListener 停止事件监听
//
//	@Summary		Stop event listener
//	@Description	Stop listening for events on a connection
//	@Tags			Event
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Success		200				{object}	map[string]string
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/events/stop [post]
func (h *EventHandler) StopEventListener(c *gin.Context) {
	connID := c.Param("connection_id")

	if err := h.eventService.StopListening(c.Request.Context(), connID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Event listener stopped"})
}

// GraphicsHandler 图形控制台处理器
type GraphicsHandler struct {
	graphicsProxy *console.GraphicsProxy
	logger        *logrus.Logger
}

func NewGraphicsHandler(graphicsProxy *console.GraphicsProxy, logger *logrus.Logger) *GraphicsHandler {
	return &GraphicsHandler{
		graphicsProxy: graphicsProxy,
		logger:        logger,
	}
}

// GetVNCInfo 获取 VNC 信息
//
//	@Summary		Get VNC information
//	@Description	Get VNC connection information for a VM
//	@Tags			Graphics
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			vm_name			path		string	true	"VM Name"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/vms/{vm_name}/graphics/vnc [get]
func (h *GraphicsHandler) GetVNCInfo(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")

	info, err := h.graphicsProxy.GetVNCInfo(c.Request.Context(), connID, vmName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": info})
}

// HandleVNCWebSocket 处理 VNC WebSocket
//
//	@Summary		Handle VNC WebSocket connection
//	@Description	Establish a WebSocket connection for VNC console
//	@Tags			Graphics
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			vm_name			path		string	true	"VM Name"
//	@Success		101				{string}	string	"Switching Protocols"
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/vms/{vm_name}/graphics/vnc/ws [get]
func (h *GraphicsHandler) HandleVNCWebSocket(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")

	if err := h.graphicsProxy.HandleVNCWebSocket(c.Writer, c.Request, connID, vmName); err != nil {
		h.logger.WithError(err).Error("VNC WebSocket handler error")
	}
}

// GetSPICEInfo 获取 SPICE 信息
//
//	@Summary		Get SPICE information
//	@Description	Get SPICE connection information for a VM
//	@Tags			Graphics
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			vm_name			path		string	true	"VM Name"
//	@Success		200				{object}	map[string]interface{}
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/vms/{vm_name}/graphics/spice [get]
func (h *GraphicsHandler) GetSPICEInfo(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")

	info, err := h.graphicsProxy.GetSPICEInfo(c.Request.Context(), connID, vmName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": info})
}

// HandleSPICEWebSocket 处理 SPICE WebSocket
//
//	@Summary		Handle SPICE WebSocket connection
//	@Description	Establish a WebSocket connection for SPICE console
//	@Tags			Graphics
//	@Param			connection_id	path		string	true	"Connection ID"
//	@Param			vm_name			path		string	true	"VM Name"
//	@Success		101				{string}	string	"Switching Protocols"
//	@Failure		500				{object}	map[string]string
//	@Router			/connections/{connection_id}/vms/{vm_name}/graphics/spice/ws [get]
func (h *GraphicsHandler) HandleSPICEWebSocket(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")

	if err := h.graphicsProxy.HandleSPICEWebSocket(c.Writer, c.Request, connID, vmName); err != nil {
		h.logger.WithError(err).Error("SPICE WebSocket handler error")
	}
}
